﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.IO;
using log4net;
using Microsoft.Xna.Framework.Input;
using Engine.Messaging.Messages;

namespace Engine.Input.Handling.KeyboardHandling
{
    public class KeyInputBinding
    {
        #region Properties
        public Keys Keys { get; set; }
        public string PressedMessage { get; set; }
        public string ReleasedMessage { get; set; }
        #endregion // Properties


        #region Methods
        internal void OnKeyDown(IInputHandler callingHandler)
        {
            if (PressedMessage != null)
                callingHandler.System.BroadcastMessage(callingHandler, new TextMessage(PressedMessage));
        }

        internal void OnKeyUp(IInputHandler callingHandler)
        {
            if (ReleasedMessage != null)
                callingHandler.System.BroadcastMessage(callingHandler, new TextMessage(ReleasedMessage));
        }
        #endregion // Methods




        #region STATIC
        private static ILog Logger { get; set; }
        static KeyInputBinding()
        {
            Logger = LogManager.GetLogger(typeof(KeyInputBinding));
        }

        public static List<KeyInputBinding> LoadFromFile(string filename = "key_input.xml")
        {
            var bin = new List<KeyInputBinding>();
            if (File.Exists(filename))
            {
                XmlSerializer s = new XmlSerializer(typeof(List<KeyInputBinding>));
                FileStream fs = new FileStream(filename, FileMode.Open);
                bin = (List<KeyInputBinding>)s.Deserialize(fs);
                fs.Close();
            }
            else
            {
                Logger.Warn(String.Format("File {0} was not found", filename));
            }
            return bin;
        }

        public static void SaveToFile(List<KeyInputBinding> bindings, string filename = "key_input.xml")
        {
            Logger.Debug(String.Format("Saving KeyInputBindings to {0}", filename));
            XmlSerializer serializer = new XmlSerializer(typeof(List<KeyInputBinding>));
            TextWriter writer = new StreamWriter(filename);
            serializer.Serialize(writer, bindings);
            writer.Close();
            Logger.Debug(String.Format("KeyInputBindings saved to {0}", filename));
        }
        #endregion // STATIC
    }
}
